package auth

import (
	"context"
	"errors"
	"log"

	pb "gitee.com/jiebaiyou/demo-grpc/protos/auth/v1"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

type Client struct {
	client pb.AuthServiceClient
}

func NewClient(addr string) *Client {
	log.Printf("Attempting to connect to auth service at %s", addr)
	conn, err := grpc.NewClient(
		addr,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
	)
	if err != nil {
		log.Fatalf("Failed to connect to auth service: %v", err)
	}
	log.Printf("Successfully connected to auth service")
	return &Client{client: pb.NewAuthServiceClient(conn)}
}

func (c *Client) Register(ctx context.Context, req *pb.RegisterRequest) (*pb.RegisterResponse, error) {
	resp, err := c.client.Register(ctx, req)
	if err != nil {
		log.Printf("could not register: %v", err)
		return nil, errors.New("could not register")
	}
	return resp, nil
}

func (c *Client) Login(ctx context.Context, req *pb.LoginRequest) (*pb.LoginResponse, error) {
	resp, err := c.client.Login(ctx, req)
	if err != nil {
		log.Printf("could not login: %v", err)
		return nil, errors.New("could not login")
	}
	return resp, nil
}
